<template>
    <el-dialog
        :visible.sync="dialogVisible"
        title="选择位置"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        width="900px"
        :modal="true"
        append-to-body
    >
        <el-form :model="formData" label-width="80px">
            <el-form-item label="详细地址" prop="address">
                <el-input v-model="formData.address" id="tipinput" :autofocus="true"/>
                <div v-if="formData.orderConfig.carParkId" style="height:36px;">
                    <div v-if="formData.address">
                        <div v-if="formData.inPolygonInfo">{{formData.inPolygonInfo.fenceNameShort}}区域，附加费：<span style="color:#F00; ">{{formData.inPolygonInfo.additionalFee}}元</span></div>
                        <div v-else style="color:#F00; ">不在可订票范围</div>
                    </div>
                </div>
            </el-form-item>
            <!-- <el-form-item label="当前坐标">
                <div v-if="formData.lng">{{ formData.lng }},{{ formData.lat }}</div>
            </el-form-item> -->
            <div id="container" style="width:860px; height:500px"/>
        </el-form>

        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false" @onConfirm="submitForm()">取 消</el-button>
            <el-popconfirm title="确定当前位置吗？" @onConfirm="submitForm()">
                <el-button slot="reference" type="primary">确定</el-button>
            </el-popconfirm>
        </div>
    </el-dialog>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import {Common} from '@/utils/common'
import {CarParkFenceApi} from '@/api/intercity/CarParkFenceApi'

export default {
    name: 'GMapSelect',
    data() {
        return {
            formData: {
                provinceName: '',
                cityName: '',
                districtName: '',
                streetName: '',
                districtCode: '',
                address: '',
                lng: '',
                lat: '',
                inPolygonInfo:null,
                orderConfig:{
                    carParkId:'',
                    fenceList:[]
                }
            },
            dialogVisible: false,
            isLoadingMap: true,
            map: null,
            geocoder: null,
            autoComplete: null,
            placeSearch: null,


            //地图覆盖物
            polygonListGroups:{},
            textListGroups:{},
            marker:{},
        }
    },
    methods: {
        // 显示组件
        showMap(data) {
            console.log('data',data)
            this.formData = Common.assign(this.formData, data)

            this.dialogVisible = true
            if (this.isLoadingMap) {
                this.loadMap(data)
            } else {
                this.setMap(data)
                if(this.formData.orderConfig.carParkId){
                    this.setPolygon()
                }
            }
        },

        loadMap(data) {
            const that = this
            that.isLoadingMap = false

            window._AMapSecurityConfig = {
                securityJsCode: process.env.VUE_APP_GAODE_SECRET_KEY,
            };
            AMapLoader.load({
                'key': process.env.VUE_APP_GAODE_KEY, // 申请好的Web端开发者Key，首次调用 load 时必填
                'version': '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                'plugins': ['AMap.Geocoder', 'AMap.AutoComplete', 'AMap.PlaceSearch'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
                'AMapUI': { // 是否加载 AMapUI，缺省不加载
                    'version': '1.1', // AMapUI 缺省 1.1
                    'plugins': [] // 需要加载的 AMapUI ui插件
                },
                'Loca': { // 是否加载 Loca， 缺省不加载
                    'version': '2.0' // Loca 版本，缺省 1.3.2
                }
            }).then((AMap) => {
                const lng = data.lng ? data.lng : 102.709308
                const lat = data.lat ? data.lat : 25.046206
                that.map = new AMap.Map('container', {
                    zoom: 11, // 级别
                    center: [lng, lat] // 中心点坐标
                })

                that.geocoder = new AMap.Geocoder({
                    city: '昆明', // 城市设为北京，默认：“全国”
                    radius: 1000 // 范围，默认：500
                })

                that.setMap(data)

                that.map.on('click', function (e) {
                    const data = {
                        lng: e.lnglat.getLng(),
                        lat: e.lnglat.getLat()
                    }
                    that.setMap(data)
                })

                that.searchMap();

                if(that.formData.orderConfig.carParkId){
                    that.setPolygon()
                }
            }).catch(e => {
            })
        },
        setPolygon(){
            let that = this

            if(that.polygonListGroups && Object.keys(that.polygonListGroups).length > 0){
                that.map.remove(that.polygonListGroups);
                that.map.remove(that.textListGroups);
            }

            let colors = ['#1791fc','#aa0000','#005500','#00aa00','#aaaa00','#00ff00','#55aa7f','#ff5500','#55aa7f','#ffff7f','#5555ff','#ff00ff']

            //添加围栏
            let polygonList = []
            let textList = []
            that.formData.orderConfig.fenceList.forEach(function(item,index,arr){
                polygonList.push(
                    new AMap.Polygon({
                        path: JSON.parse(item.points),
                        strokeColor: '#FF33FF',
                        strokeWeight: 1,
                        strokeOpacity: 0.2,
                        fillOpacity: 0.2,
                        fillColor: colors[index],
                        zIndex: item.sort,
                        bubble: true
                    })
                )

                textList.push(
                    new AMap.Text({
                        text: item.fenceNameShort,
                        anchor:'center', // 设置文本标记锚点
                        // angle:10,
                        style:{
                            'padding': '.3rem .3rem',
                            'border-radius': '.25rem',
                            'background-color': 'white',
                            'width': '5rem',
                            'border-width': 0,
                            'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
                            'text-align': 'center',
                            'font-size': '14px',
                            'color': 'black'
                        },
                        position: [item.lng,item.lat]
                    })
                )
            })
            that.polygonListGroups = new AMap.OverlayGroup(polygonList);
            that.map.add(that.polygonListGroups)

            that.textListGroups = new AMap.OverlayGroup(textList);
            that.map.add(that.textListGroups)
            that.map.setFitView();

        },
        setMap(data) {
            const that = this
            that.formData.lng = data.lng
            that.formData.lat = data.lat
            that.formData.address = data.address
            that.formData.districtCode = data.districtCode

            that.map.remove(that.marker)
            if (data.lng && data.lat) {
                that.marker = new AMap.Marker({
                    position: [data.lng, data.lat]
                })
                that.map.add(that.marker)
                that.map.setCenter([data.lng,data.lat])
            }

            if (data.lng && data.lat) {
                that.geocoder.getAddress([data.lng, data.lat], function (status, result) {
                    if (status === 'complete' && result.regeocode) {

                        if (!that.formData.address) {
                            that.formData.address = result.regeocode.formattedAddress
                        }
                        that.formData.provinceName = result.regeocode.addressComponent.province
                        that.formData.cityName = result.regeocode.addressComponent.city
                        that.formData.districtName = result.regeocode.addressComponent.district
                        that.formData.streetName = result.regeocode.addressComponent.township
                        that.formData.districtCode = result.regeocode.addressComponent.adcode

                        if(that.formData.orderConfig.carParkId){
                            data['carParkId'] = that.formData.orderConfig.carParkId
                            CarParkFenceApi.inPolygon(data).then((response) => {
                                if(response){
                                    response.additionalFee = response.additionalFee / 100
                                }
                                that.formData.inPolygonInfo = response
                            })
                        }
                        console.log("坐标搜索结果：", result.regeocode)
                    } else {
                        console.log('根据经纬度查询地址失败')
                    }
                })
            }
        },

        searchMap() {
            // 搜索框自动完成类
            this.autoComplete = new AMap.AutoComplete({
                input: "tipinput",
                city: '昆明'
            });

            // 当选中某条搜索记录时触发
            this.autoComplete.on("select", this.selectSite);
        },

        //当选中某条搜索记录时触发
        selectSite(e) {
            let that = this
            let data = {
                lng: e.poi.location.lng,
                lat: e.poi.location.lat
            }
            that.setMap(data)
        },

        submitForm() {
            this.$emit('bindMapInfo', this.formData)
            this.dialogVisible = false
        }
    }
}
</script>
<style>
.amap-sug-result {
    z-index: 2999;
}
</style>
